<?php

namespace app\langjinmobile\controller;
//导入基类
use think\Controller;
use think\facade\Cache;
use think\Db;
use app\common\model\User as userModel;
use app\common\model\Sendmsg as SendmsgModel;
use app\common\model\UserLevel as userLevelModel;
use app\common\model\Money as moneyModel;

class Registered extends Controller 
{	
	//  注册
	public function registered($id=''){
        $user = userModel::field('mobile')->where('id',$id)->find();
        $this->assign('mobile',$user['mobile']);
		return $this->fetch(); 
	}
	// 登录
	public function login(){
		return $this->fetch(); 
	}
	// 忘记密码
	public function forgetpass(){
		return $this->fetch(); 
    }
    // 忘记支付密码
	public function forgetpaypass(){
		return $this->fetch(); 
    }
	//验证码
	public function code(){
		//判断手机号是否注册过
            $mobile = userModel::where('mobile',Request()->param('mobile'))->find();
            $phone = Request()->param('mobile');
            $type = request()->param('type','1');
            if($mobile != null && $type !=2){
                // $this->error(lang('该手机号没有注册'));
                echo 7;exit;
                $msg = lang("该手机号已经注册");
            }else{
                if(session('code_time')){
                  $time1 = time();
                  $time2 = session('code_time');
                  $time = $time1 - $time2;
                  if($time<60){
                    echo 3;exit;
                  }
                }
                //判断开始国内 还是国外
                $smsid=SendmsgModel::where('status',1)->find();//开启的短信接口
                if($smsid['id'] == 1){
                    $code = rand(1,9999);
                    Session('code',$code);
                    Session('mobile',$phone);
                    header('content-type:text/html;charset=utf-8');
                    //查询短信配置表
                    $msm = SendmsgModel::where('id',1)->find();
                    $sendUrl = $msm['sendUrl']; //短信接口的URL http://v.juhe.cn/sms/send

                    $smsConf = array(
                        'key'   => $msm['appkey'], //您申请的APPKEY 262ff79e6e341470472bb952c4fd8635
                        'mobile'    => $phone, //接受短信的用户手机号码
                        'tpl_id'    => $msm['tpl_id'], //您申请的短信模板ID，根据实际情况修改 84460
                        'tpl_value' =>'#code#='.$code //您设置的模板变量，根据实际情况修改
                    );

                    $content = $this->juhecurl($sendUrl,$smsConf,1); //请求发送短信

                    if($content){
                        $result = json_decode($content,true);
                        $error_code = $result['error_code'];
                        if($error_code == 0){
                            session('code_time',time());
                            echo 1;
                            //状态为0，说明短信发送成功
                            // echo "短信发送成功,短信ID：".$result['result']['sid'];
                        }else{
                            return [
                                'code'  =>  2,
                                'msg'   =>  '短信接口错误错误代码'.$result['error_code'],
                            ];
                        }
                    }else{
                        echo 3;
                        $msg = lang("请求发送短信失败");
                    }
                }else{//国际短信

                    header('content-type:text/html;charset=utf-8');
                    $code = mt_rand(100000,999999);
                    Session('code',$code);
                    Session('mobile',$phone);
                    if(Request()->param('area')){
                        $phone = Request()->param('area').$phone;
                    }else{
                        $phone = $phone;
                    }
                    $result = $this->sendInternational($phone, '【PEX Wallet】Your verification code is '.$code);
                    if(!is_null(json_decode($result))){
                        $output=json_decode($result,true);
                        if(isset($output['code'])  && $output['code']=='0'){
                            // echo '短信发送成功！' ;
                            echo 1;
                        }else{
                            echo $output['error'];
                        }
                    }else{
                        echo $result;
                    }
                }
            }
	}



	/**
     * 执行聚合短信接口
     */
    public function juhecurl($url,$params=false,$ispost=0){
            $httpInfo = array();
            $ch = curl_init();
            curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
            curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
            curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
            curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
            curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
            if( $ispost )
            {
                curl_setopt( $ch , CURLOPT_POST , true );
                curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
                curl_setopt( $ch , CURLOPT_URL , $url );
            }
            else
            {
                if($params){
                    curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
                }else{
                    curl_setopt( $ch , CURLOPT_URL , $url);
                }
            }
            $response = curl_exec( $ch );
            if ($response === FALSE) {
                //echo "cURL Error: " . curl_error($ch);
                return false;
            }
            $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
            $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
            curl_close( $ch );
            return $response;
    }


    /**
      * 操作注册
      */
    public function doregister(){

          $code = Request()->param('code');
          $token = Request()->param('__token__');
          $data['mobile'] = Request()->param('phone');//电话
          $data['nickname'] = Request()->param('nickname');//昵称
          $data['pwd'] = Request()->param('pwd');//登录密码
          $data['safety_pwd'] = Request()->param('safety_pwd');//支付密码
          $data['level'] = 0;//等级
          $data['parent_id'] = Request()->param('parent_id');//上级
          $data['parent_id']?$data['parent_id']:"";
          $data['create_time'] = time();//创建时间
          $data['update_time'] = time();//更新时间
          $data['disable'] = 1;//状态 1可以 0不可用
          $data['is_business'] = 0;//商家
// dump($code);dump(session('code'));die('dsssa');
          //密码加密
          $salt= substr(md5(time()),0,3);
          $data['pwd'] = pwdMd5($data['pwd'],$salt);
          $data['login_salt']=$salt;
          $data['safety_pwd'] = pwdMd5($data['safety_pwd'],$salt);
          $data['safety_salt']=$salt;

          //判断手机号是否注册过
          $mobile = userModel::where('mobile',$data['mobile'])->find();
          if($mobile != null){
              $this->error('该手机号注册过');
          }
          if($data['mobile'] != session('mobile')){
              $this->error('网络繁忙稍后再试');
          }

          if(!preg_match("/^1[345678]{1}\d{9}$/",$data['mobile'])){
              $this->error(lang('请输入正确的手机号'));
          }
          //判断填写的推荐人是否存在
          if($data['parent_id'] != ""){

              $last_user = userModel::where('mobile',$data['parent_id'])->field('id,path')->find();
              if(!$last_user){
                  $this->error('没有该推荐人');
              }else{                
                  if($code==Session('code') && $code !=''){
                    Db::startTrans();
                    try{
                        //path路径
                        $path=$last_user['path'];
                        if(empty($path)){
                        $data['path']=$last_user['id'].',';
                        }else{
                        $data['path']=$path.$last_user['id'].',';
                        }
                        //1.user表添加数据
                        $data['parent_id'] = $last_user['id'];
                        $data['head_img'] = '/static/langjinmobile/images/userhead_img.png';
                        session('code',null);
                        Session('mobile',null);
                        $max_uid = userModel::max('id');              
                        $data['id'] = $max_uid + mt_rand(111, 333);
                        $userid = userModel::insertGetId($data);
                        // 2.创建用户等级
			            $infos['userid'] = $userid;//用户id
			            $infos['user_grade'] = 0;//用户等级
			            $infos['level_grade'] = 0;//用户VIP等级
			            //$infos['assets_grade'] = 0;//币的等级
			            userLevelModel::insert($infos);
			            //3注册money表
			            //$integral_num = rewardModel::where('group','7')->field('value')->find();//查询设置里group=7的值
			           $money['userid'] = $userid;
			           $money['balance'] = '0';
			           $money['integral'] = '0';
			           $money['create_time'] = time();
			           moneyModel::insert($money);//money表添加数据
                        
                        
                        
                        

                        Db::commit();
                        return $data = ['code'=>1, 'msg'=>'注册成功', 'url'=>'/langjinmobile/Login/login'];
                        // $this->success(lang('注册成功'),'mobile/login/login');

                    }catch(\Exception $e){
                        // echo $e;
                        Db::rollback();
                        $this->error(lang('注册失败'));
                    }

                  }else{

                       $this->error(lang('短信验证码错误'));
                  }

              }

          }else{
                  $this->error(lang('请填写推荐人'));

          }
    }


    /**
     * 操作登录
     */
    public function dologin()
    {
        $mobile = Request()->param('mobile');
        $pwd = Request()->param('pwd');
        $user = userModel::where('mobile',$mobile)->whereOr('id',$mobile)->find();
        if($user){
          if($user['disable']==0){
              $result = array(['type'=>4,'msg'=>$mobile]);
              echo json_encode($result);
          }else{
             //验证密码方法
             if(pwdMd5($pwd,$user['login_salt'])==$user['pwd']){
                session('userid', $user['id']);
                 clear_jiangli($user['id']);
                $result = array(['type'=>1]);
                echo json_encode($result);
              }else{
                  $result = array(['type'=>3,'msg'=>$mobile]);
                  echo json_encode($result);
              }
          }

        }else{
            $result = array(['type'=>2]);
            echo json_encode($result);
        }
    }


    /**
     * 找回密码
     */
    public function getPsw()
    {   
        $code = Request()->param('code');
        $data['mobile'] = Request()->param('phone');
        $data['pwd'] = Request()->param('pwd');
        $salt = substr(md5(time()),0,3);
        $data['pwd'] = pwdMd5($data['pwd'],$salt);

      if($data['mobile']){
          $mobile = userModel::where('mobile',$data['mobile'])->find();
          if($mobile == null){
                $this->error(lang('该手机号不是会员'),'langjinmobile/registered/registered');
          }else{
              if($code==Session('code') && $code !=''){
                     session('code',null);
                     session('userid',null);
                     userModel::where('mobile',$data['mobile'])->update(['pwd' => $data['pwd'],'login_salt'=>$salt]);
                     $this->success('ok');
               }else{
                     $this->error(lang('验证码错误'));
               }
           }
       }
       
    }


    /**
     * 退出登录
     */
    public function logout()
    {
        session('userid', null);
        $this->success('退出成功', 'langjinmobile/registered/login');
    }


    /**
     * 找回支付密码
     */
    public function getPswpay()
    {
          $mobile = userModel::where('id',session('userid'))->value('mobile');
          $code = Request()->param('code');

          $data['mobile'] = Request()->param('phone');
          $data['pwd'] = Request()->param('pwd');
          $salt = substr(md5(time()),0,3);
          $data['pwd'] = pwdMd5($data['pwd'], $salt);

          if($data['mobile']){
           if($code==Session('code') && $code !=''){
             session('code',null);
             userModel::where('mobile',$data['mobile'])->update(['safety_pwd' => $data['pwd'], 'safety_salt'=>$salt]);
             $this->success('ok');
           }else{
             $this->error(lang('短信验证码错误'));
           }
          }
         //查找area表
         $area = AreaModel::select();
         $this->assign('area',$area);
         $sms = SendmsgModel::where('status',1)->field('id')->find();   
         $this->assign('smsid',$sms['id']);//短信id
         $this->assign('mobile',$mobile);
         return $this->fetch();
    }




}